package dyy.zc.alumnibook.ui.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.datatype.BmobFile;
import dyy.zc.alumnibook.R;
import dyy.zc.alumnibook.base.BaseFragment;
import dyy.zc.alumnibook.bean.Friend;
import dyy.zc.alumnibook.bean.UserInfo;
import dyy.zc.alumnibook.listener.OnItemFriendClick;
import dyy.zc.alumnibook.ui.activity.FriendHomePageActivity;
import dyy.zc.alumnibook.ui.adapter.FriendAdapter;
import dyy.zc.alumnibook.utils.BmobUtils;
import dyy.zc.alumnibook.utils.StringUtils;
import dyy.zc.alumnibook.utils.ToastUtils;
import dyy.zc.alumnibook.utils.Utils;
import dyy.zc.alumnibook.views.BottomPopwindows2;
import dyy.zc.alumnibook.views.MyAlertDialog;

/**
 * 我的好友
 * Created by chuan on 2017/4/12.
 */

public class FriendFragment extends BaseFragment implements View.OnClickListener {
    private final int SUCCESS = 1;
    private final int FAILED = 404;
    private final int FENZU_SUCCESS = 123;
    private final int ADD_SUCCESS = 234;
    private final int FIND_SUCCESS = 456;
    private View view;
    private TextView title;
    private RecyclerView recyclerView;
    private FriendAdapter adapter;
    private List<Friend> list = new ArrayList<>();
    private BmobUtils bmobUtils;
    private UserInfo userInfo;
    /**
     * 这里是点击好友用的接口
     * parent：表示第几个分组
     * position：表示第几个好友
     */
    private String account;//好友的账号
    /**
     * 点击查看他的朋友圈跳转
     */
    private View.OnClickListener checkFriendCircle = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), FriendHomePageActivity.class);
            intent.putExtra("account", account);
            startActivity(intent);
        }
    };
    private OnItemFriendClick friendListener = new OnItemFriendClick() {
        @Override
        public void onFriendClick(int parent, int position) {
            Friend friend = list.get(parent);
            account = friend.getFriendAccount().get(position);
            BottomPopwindows2 bottomPopwindows2 = new BottomPopwindows2(getActivity(), friend, position, checkFriendCircle);
            bottomPopwindows2.showAtLocation(view, Gravity.BOTTOM, 0, 0);
        }
    };
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SUCCESS:
                    dialog.dismiss();
                    Bundle bundle = msg.getData();
                    userInfo = (UserInfo) bundle.getSerializable("friend");
                    if (list.size() == 0) {
                        createZu(userInfo);
                    } else {
                        chooseFenZu();
                    }
                    break;
                case FAILED:
                    dialog.dismiss();
                    ToastUtils.shortToast(getActivity(), "无此用户");
                    break;
                case FENZU_SUCCESS:
                    Bundle bundle1 = msg.getData();
                    Friend friend = (Friend) bundle1.getSerializable("friend");
                    list.add(friend);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    dialog.dismiss();
                    break;
                case ADD_SUCCESS:
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    dialog.dismiss();
                    break;
                case FIND_SUCCESS:
                    Bundle bundle2 = msg.getData();
                    List<Friend> friendList = (List<Friend>) bundle2.getSerializable("friend");
                    list.clear();
                    list.addAll(friendList);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    };
    private View.OnClickListener chooseListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (datePicker.getCurrentItemPosition() == (strings.size() - 1)) {
                createZu(userInfo);
            } else {
                //添加好友
                dialog = ProgressDialog.show(getActivity(), null, "正在添加好友");
                Friend friend = list.get(datePicker.getCurrentItemPosition() - 1);
                friend.getName().add(userInfo.getName());
                friend.getHead().add(userInfo.getHead());
                friend.getFriendAccount().add(userInfo.getAccount());
                bmobUtils.updateFriend(friend, ADD_SUCCESS, handler);
            }
            mPopupWindow.dismiss();
        }
    };

    @Override
    protected View onCreateViews(LayoutInflater inflater, ViewGroup container) {
        view = inflater.inflate(R.layout.fragment_friend,container,false);
        findIDs(view);
        initData();
        bind();
        return view;
    }

    private void bind() {
        Utils.findViewsById(view,R.id.add).setOnClickListener(this);

    }

    private void initData() {
        bmobUtils = new BmobUtils(getActivity());
        Utils.findViewsById(view,R.id.top_rl_back).setVisibility(View.GONE);
        adapter = new FriendAdapter(getActivity(),list,friendListener);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);
        bmobUtils.queryFriendList(loginuser,FIND_SUCCESS,handler);
    }

    private void findIDs(View view) {
        title = Utils.findViewsById(view,R.id.top_tv_title);
        recyclerView = Utils.findViewsById(view,R.id.recyclerView);
        title.setText("朋友");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.add:
                addFriend();
                break;
        }
    }

    private void addFriend() {
        final MyAlertDialog logDialog = new MyAlertDialog(getActivity());
        final EditText editText = new EditText(getActivity());
        editText.setTextColor(getActivity().getResources().getColor(R.color.colorBlack));
        logDialog.builder()
                .setTitle("请输入好友账号")
                .setView(editText)
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                })
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String account = editText.getText().toString();
                        if (!StringUtils.isEmpty(account)){
                            if (findisMyFriend(account)){
                                ToastUtils.shortToast(getActivity(),"已添加该好友");
                            }else {
                                if (!account.equals(loginuser.getAccount())){
                                    findFriend(account);
                                }else {
                                    ToastUtils.shortToast(getActivity(),"不能添加自己为好友");
                                }
                            }


                        }else {
                            ToastUtils.shortToast(getActivity(),"请输入名字");
                        }

                    }
                })
                .show();
    }

    public boolean findisMyFriend(String account){
        for (Friend friend:list){
            for (String n:friend.getFriendAccount()){
                if (account.equals(n)){
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 查找是否存在此好友
     */
    private void findFriend(String account) {
        dialog = ProgressDialog.show(getActivity(),null,"正在查找好友");
        bmobUtils.findFriend(account,SUCCESS,handler);
    }

    /**
     * 选择分组
     */
    private List<String> strings;
    private void chooseFenZu() {
        strings = new ArrayList<>();
        for (Friend friend:list){
            strings.add(friend.getZuming());
        }
        strings.add("添加新分组");
        initPopUpWindow(strings,chooseListener);
    }

    /**
     * 创建分组
     * @param userInfo
     */
    private void createZu(final UserInfo userInfo) {
        final MyAlertDialog logDialog = new MyAlertDialog(getActivity());
        final EditText editText = new EditText(getActivity());
        editText.setTextColor(getActivity().getResources().getColor(R.color.colorBlack));
        logDialog.builder()
                .setTitle("请输入分组名称")
                .setView(editText)
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                })
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String name = editText.getText().toString();
                        if (!StringUtils.isEmpty(name)){
                            dialog = ProgressDialog.show(getActivity(),null,"正在添加好友");
                            Friend friend = new Friend();
                            List<String> nameList = new ArrayList<>();
                            List<String> accountList = new ArrayList<>();
                            List<BmobFile> headList = new ArrayList<>();
                            nameList.add(userInfo.getName());
                            headList.add(userInfo.getHead());
                            accountList.add(userInfo.getAccount());
                            friend.setZuming(name);
                            friend.setId(loginuser.getId());
                            friend.setHead(headList);
                            friend.setName(nameList);
                            friend.setFriendAccount(accountList);
                            bmobUtils.saveFenzu(friend,FENZU_SUCCESS,handler);

                        }else {
                            ToastUtils.shortToast(getActivity(),"名称不能为空");
                        }

                    }
                })
                .show();
    }
}
